#!/usr/bin/php
<?php

namespace co2_OS;

define('co2_OS_base',__DIR__);

//	launch main class
require_once co2_OS_base.'/motor/boot/class.main.php';
	
new main;

foreach(scandir($boot=__DIR__.'/motor/boot') as $file)
if($file!='.'&&$file!='..')

{
	$e=explode('.',$file,3);
	
	if($e[0]=='function')
	require_once "$boot/$file";
	
	if($e[0]=='class'&&$e[1]!='main')
	require_once "$boot/$file";
}

main::getLinuxUser()=='root'	or	exit('You must be root'.PHP_EOL);

spl_autoload_register('co2_OS\autoload');







require_once 	co2_OS_base.'/motor/co2-api/co2.php';

new \co2\runtime((object)array(
	'properties'=>
	array
	(
		'catch php errors'		=>	true
	),
	'error_handlers'=>
	array
	(
		function($level,$message,$file,$line,$context)
		{
			throw new \co2\Exception($message,null,$level,$file,$line,$context);
		}
	)
));















if(!isset($argv[1]))
{
	$version=main::getSysVar('kernel-version');

	exit(<<<USAGE
===========================================================
Welcome to co2 embedded operating system version $version!
===========================================================


USAGE
);
}

try
{
	switch($action=$argv[1])
	
	{
		default:
		
			throw new \co2\Exception('Unknown action');
		
		break;
		
		case'run':
		
			if(!isset($argv[2]))
			throw new \co2\Exception('Nothing to run');
			
			$app=preg_replace('/-/','_',$argv[2]);
			
			$run=run($app);
			
			if(isset($argv[3]))
			
			{
				$method=preg_replace('/-/','_',$argv[3]);
				
#				if(!method_exists($run,$method))
#				throw new \co2\Exception('Called to an unknown app method: '.$app.'::'.$method);
			
				for($args=array(),$array=null,$object=null,$object_key=null,$i=4; $i<$argc; $i++)
				
				{
					if($argv[$i]=='[')
					$array=array();
					
					elseif(is_array($array) && $argv[$i]!=']')
					$array[]=arg2var($argv[$i]);
					
					elseif($argv[$i]==']' && is_array($array))
					
					{
						$args[]=$array;
						
						$array=null;
					}
					
					elseif($argv[$i]=='{')
					$object=new \stdClass;
					
					elseif(is_object($object) && $argv[$i]!='}')
					
					{
						if(preg_match('/^--/',$argv[$i]) && is_null($object_key))
						$object_key=preg_replace('/^--/','',$argv[$i]);
						
						elseif(is_string($object_key))
						
						{
							$object->$object_key=arg2var($argv[$i]);
							
							$object_key=null;
						}
					}
					
					elseif(is_object($object) && $argv[$i]=='}')
					
					{
						$args[]=$object;
						
						$object=null;
					}
					
					else
					$args[]=arg2var($argv[$i]);
				}

				$run2=call_user_func_array(array($run,$method),$args);
				
				if(method_exists($run2,'__toString'))
				echo $run2.PHP_EOL;
			}
		
		break;
		
		case'install':
		
			if(!isset($argv[2]))
			throw new \co2\Exception('Nothing to install');
			
			$app=preg_replace('/-/','_',$argv[2]);
			
			if(!isset($argv[3]))
			throw new \co2\Exception('Missing app version');
			
			$version=$argv[3];
			
			install($app,$version);
			
			echo "$app v$version successfully installed",PHP_EOL;
		
		break;
		
		case'uninstall':
		
			if(!isset($argv[2]))
			throw new \co2\Exception('Nothing to uninstall');
			
			$app=preg_replace('/-/','_',$argv[2]);
			
			uninstall($app);
			
			echo "$app successfully uninstalled",PHP_EOL;
		
		break;
		
		case'backup':
		
			echo gmdate('H:i:s').'> compressing data',PHP_EOL;
			
			flush();
			
			new \co2\bash\tar(main::getSysVar('base'),$tmp=uniqid('tmptar_',true),'j');
			new \co2\bash\mv($tmp,$bkp=main::getSysVar('tmp').'/co2.bkp.q');

			echo gmdate('H:i:s').'> sending data to Amazon',PHP_EOL;
			
			flush();
			
			$date=time();
			
			$bash=new \co2\bash(main::getSysVar('lib').'/s3cmd/'.s3cmd_version.'/s3cmd --config='.main::getSysVar('conf').'/s3cfg put '.$bkp.' s3://'.s3_bucket_prefix.main::getSysVar('client-number').'/co2.'.$date.'.bkp');
			
			$bash->exec(new \co2\String\RegEx('/\[1 of 1\]$/'));
			
			echo gmdate('H:i:s').'> co2 client successfully backed up to amazon s3',PHP_EOL;
			
			new \co2\bash\rm($bkp);
		
		break;
		
		case'info':
		
			if(isset($argv[2]))
			
			{
				$app=$argv[2];
			
				$app=new app($app);
				
				if(!$app->exists())
				throw new \co2\Exception("$app? No such app!");
			
				$version=isset($argv[3])?$argv[3]:main::getAppsManifest()->$app;
				
				$readme=$app->getBase().'/v'.preg_replace('/\./','/v',$version).'/README.txt';
				
				if(!file_exists($readme))
				throw new \co2\Exception('app has no read-me');
				
				echo '
'.$app.' '.$version.'
=============			READ ME		===================
'.file_get_contents($readme);
			}
			
			else
			
			{
				echo '----------------------------------------------------
                   GENERAL
````````````````````````````````````````````````````
           Kernel version: ',main::getSysVar('kernel-version'),'
              API version: ',main::getSysVar('api-version'),'
----------------------------------------------------
    INSTALLED APPLICATIONS
````````````````````````````````````````````````````';

			foreach(main::getAppsManifest() as $app=>$version)
			{
				$tab='';
				
				for($i=0;$i<25-strlen($app);$i++)
				$tab.=' ';
			
				echo "
$tab$app:  $version";
			}

			echo
PHP_EOL,
PHP_EOL;
			}
			
		break;
	}
}
catch(\co2\Exception $e)
{
	echo 'Error caught... ','"',$e->getMessage(),'"',PHP_EOL,$e->getFile(),':',$e->getLine(),PHP_EOL
	#,print_r($e->getContext(),1)
	;
}
